<template>
  <div class="articleList">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        offset="50"
        :immediate-check="false"
      >
        <ArticleItem
          :articleItem="item"
          v-for="item in articleList"
          :key="item.art_id"
          @dislike="dislike"
          @reports="reports"
          @click.native="$router.push(`/article_detail?aid=${item.art_id}`)"
        ></ArticleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import ArticleItem from "../../../components/ArticleItem.vue";
import { getArticles, getArticlesDislikes, getArticlesReports } from "@/api";
export default {
  props: {
    cid: {
      type: Number,
      default: 0,
    },
  },
  components: {
    ArticleItem,
  },
  data() {
    return {
      // 底部加载状态
      loading: false,
      // 数据是否全部加载完成
      finished: false,
      // 文章列表
      articleList: [],
      channel_id: this.cid,
      // 用于加载更多(分页)
      nextTime: null,
      // 顶部刷新状态
      refreshing: false,
    };
  },
  created() {
    this.getArticles();
  },
  methods: {
    // 获取文章新闻推荐
    async getArticles() {
      try {
        const res = await getArticles({
          channel_id: this.channel_id,
          timestamp: this.nextTime || new Date().getTime(),
        });
        // 请求下一页的时间戳
        this.articleList = [...this.articleList, ...res.data.results];

        this.nextTime = res.data.pre_timestamp;

        if (res.data.pre_timestamp === null) {
          // 本次回来的数据是最后, 没有下一段数据了
          this.finished = true;
        }
        // 底部加载更多状态
        this.loading = false;
        // 顶部加载状态关闭
        this.refreshing = false;
      } catch (error) {
        this.$toast.fail("加载文章列表失败！");
      }
    },
    async getArticlesDislikes(id) {
      try {
        await getArticlesDislikes({ target: id });
        this.$toast("反馈成功");
      } catch (error) {
        this.$toast.fail("反馈失败！");
      }
    },
    async getArticlesReports(id, type) {
      try {
        const res = await getArticlesReports({
          target: id,
          type: type,
          remark: "就是其他问题",
        });
        this.$toast("举报成功");
      } catch (error) {
        this.$toast.fail("举报失败！");
      }
    },
    // 不感兴趣事件
    dislike(value) {
      this.getArticlesDislikes(value.art_id);
    },
    // 举报事件
    reports(obj, value) {
      this.getArticlesReports(obj.art_id, value);
    },
    // 上拉加载
    onLoad() {
      // 有第一页数据以后, onLoad再发请求
      if (this.articleList.length > 0) {
        this.getArticles();
      }
    },
    // 下拉刷新
    onRefresh() {
      this.articleList = [];
      this.nextTime = null;
      this.getArticles();
    },
  },
};
</script>

<style lang="less" scoped></style>
